# Process Rockland
library(censusxy)
library(tidyverse)
library(doParallel)

rc <- readRDS('data-raw/RC_vf.Rds')

rc <- rc %>% filter(STATUS == 'ACTIVE')

df <- rc %>%
    mutate(RADDNUMBER = str_replace_na(RADDNUMBER, ''),
           RHALFCODE = str_replace_na(RHALFCODE, ''),
           RPREDIRECTION = str_replace_na(RPREDIRECTION, ''),
           RSTREETNAME = str_replace_na(RSTREETNAME, ''),
           RPOSTDIRECTION = str_replace_na(RPOSTDIRECTION, '')) %>%
    mutate(street = str_squish(paste(RADDNUMBER, RHALFCODE, RPREDIRECTION, RSTREETNAME, RPOSTDIRECTION)))%>%
    mutate(state = 'NY') %>%
    mutate(id = row_number())

pts <- cxy_geocode(df,id = 'id',
                               street = 'street',
                               city = 'RCITY',
                               zip = 'RZIP5',
                               state = 'state',
                               output = 'simple',
                               class = 'sf', parallel = 8)


missed <- df %>% slice(which(!(1:nrow(df) %in% pts$id)))
missedpts <- cxy_geocode(missed, id = 'id',
                                     street = 'street',
                                     city = 'RCITY',
                                     #zip = 'RZIP5',
                                     state = 'state',
                                     output = 'simple',
                                     class = 'sf', parallel = 8)


found <- bind_rows(pts, missedpts)
missed <- df %>% slice(which(!(1:nrow(df) %in% found$id)))

missedpts <- cxy_geocode(missed, id = 'id',
                                     street = 'street',
                                     zip = 'RZIP5',
                                     state = 'state',
                                     output = 'simple',
                                     class = 'sf', parallel = 8)

found <- bind_rows(found, missedpts)
missed <- df %>% slice(which(!(1:nrow(df) %in% found$id)))

# Check for bad zip
missedpts <- cxy_geocode(missed, id = 'id',
                                     street = 'street',
                                     city = 'TOWNCITY',
                                     zip = 'RZIP5',
                                     state = 'state',
                                     output = 'simple',
                                     class = 'sf', parallel = 8)


found <- bind_rows(found, missedpts)
missed <- df %>% slice(which(!(1:nrow(df) %in% found$id)))

missedpts <- cxy_geocode(missed, id = 'id',
                                     street = 'street',
                                     city = 'TOWNCITY',
                                     state = 'state',
                                     output = 'simple',
                                     class = 'sf', parallel = 8)


found <- bind_rows(found, missedpts)

saveRDS(found, here('data-raw/RC_vf_sf.Rds'))
